package com.youyicloud.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.youyicloud.constants.Constants;
import com.youyicloud.sdk.Crypt;
import com.youyicloud.utils.DateUtils;
import com.youyicloud.utils.PlugFlowUtils;
import com.youyicloud.utils.WebRTCSigApi;
import com.youyicloud.vo.ResponseBodyEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value="腾讯云签名接口")
@Slf4j
@RestController
@SuppressWarnings({ "unchecked", "rawtypes" })
public class IotApi {
	@Value("${tencentInteractive.privateKeyName}")
	private String privateKeyName;// = "c:\\private_key";//私钥
	@Value("${tencentInteractive.publicKeyName}")
	private String publicKeyName;// = "c:\\public_key";//公钥
	@Value("${tencentInteractive.keyPath}")
	private String keyPath;//c:\\
	
	/**
	 * 获取安卓视频播放所需信息
	 * @param userId 用户id
	 * @param roomId 房间id
	 * @param sdkAppId// 1400060496
	 * @return
	 */
	@ApiOperation("获取安卓视频播放所需信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",name="userId",dataType="String",required=true,value="用户id",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="roomId",dataType="int",required=true,value="房间号",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="sdkAppId",dataType="Integer",required=true,value="腾讯云sdkapId",defaultValue="")
		        })
	@RequestMapping(value="getUserSig",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity getUserSig(Integer sdkAppId,String userId,int roomId){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		try {
			responseBodyEntity.setData(WebRTCSigApi.getUserSigAndPrivMapEncrypt(sdkAppId, roomId, userId, keyPath+sdkAppId+"/"+privateKeyName, keyPath+sdkAppId+"/"+publicKeyName));
			responseBodyEntity.setMsg("获取UserSig成功!");
			responseBodyEntity.setState(Constants.SUCCEED);
		} catch (Exception e) {
			responseBodyEntity.setMsg("获取UserSig失败!");
			responseBodyEntity.setState(Constants.FAILURE);
			log.error("异常信息:{}",e);
		}
		return responseBodyEntity;
	}
	
	/**
	 * 获取ios播放所需信息
	 * @param userId 用户名
	 * @param roomId 房间号
	 * @param int expired	//86400
	 * @return
	 */
	@ApiOperation("获取ios播放所需信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",name="userId",dataType="String",required=true,value="用户id",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="roomId",dataType="int",required=true,value="房间号",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="sdkAppId",dataType="Integer",required=true,value="sdkAppId",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="expired",dataType="int",required=true,value="过期时间",defaultValue="86400"),
		@ApiImplicitParam(paramType="query",name="key",dataType="String",required=true,value="权限密钥",defaultValue="")
		        })
	@RequestMapping(value="getUserSigAndSig",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity getUserSigAndSig(String key,Integer sdkAppId,String userId,int roomId,int expired){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		try {
			log.info("获取ios播放所需信息,{},{},{},{}",sdkAppId, roomId, expired, key);
			log.info("密钥读取路径为:{},{}",keyPath+sdkAppId+"/"+privateKeyName, keyPath+sdkAppId+"/"+publicKeyName);
			Map resultMap = Crypt.getSig(sdkAppId, roomId, expired, key);
			resultMap.putAll(WebRTCSigApi.getUserSigAndPrivMapEncrypt(sdkAppId, roomId, userId, readFile(keyPath+sdkAppId+"/"+privateKeyName), readFile(keyPath+sdkAppId+"/"+publicKeyName)));
			responseBodyEntity.setData(resultMap);
			responseBodyEntity.setMsg("获取UserSigAndSig成功!");
			responseBodyEntity.setState(Constants.SUCCEED);
		} catch (Exception e) {
			responseBodyEntity.setMsg("获取UserSigAndSig失败!");
			responseBodyEntity.setState(Constants.FAILURE);
			log.error("异常信息:{}",e);
		}
		return responseBodyEntity;
	}
	
	
	/**
	 * @param key	//wf8ON8dsrb4IJ7ex2rTqy3sSnsiIdiY9
	 * @param bizid	15576
	 * @param liveId 15576_2314190a47
	 * @return
	 */
	@ApiOperation("获取推流地址")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",name="key",dataType="String",required=true,value="防盗链key",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="bizid",dataType="String",required=true,value="bidId",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="liveId",dataType="int",required=true,value="直播房间id",defaultValue="")
		        })
	@RequestMapping(value="getPlugFlowUrl",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity getUserSigAndSig(String key,String bizid,String liveId){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		try {
			String safeUrl = PlugFlowUtils.getSafeUrl(key, bizid, DateUtils.getUnixDate());
			
			String prefixUrl = "rtmp://"+bizid+".livepush.myqcloud.com/live/"+bizid+"_"+liveId+"?bizid="+bizid+"&";
			
			responseBodyEntity.setData(prefixUrl+safeUrl);
			responseBodyEntity.setMsg("获取推流地址成功!");
			responseBodyEntity.setState(Constants.SUCCEED);
		} catch (Exception e) {
			responseBodyEntity.setMsg("获取推流地址失败!");
			responseBodyEntity.setState(Constants.FAILURE);
			log.error("异常信息:{}",e);
		}
		return responseBodyEntity;
	}
	
	
	/**
	 * @param key	//wf8ON8dsrb4IJ7ex2rTqy3sSnsiIdiY9
	 * @param bizid	15576
	 * @param liveId 15576_2314190a47
	 * @return
	 */
	@ApiOperation("获取播放地址")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",name="bizid",dataType="int",required=true,value="bidId",defaultValue=""),
		@ApiImplicitParam(paramType="query",name="liveId",dataType="String",required=true,value="直播房间id",defaultValue="")
		        })
	@RequestMapping(value="getPlayUrl",method= {RequestMethod.GET,RequestMethod.POST})
	public ResponseBodyEntity getPlayUrl(String bizid,String liveId){
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		try {
			String rtmpUrl = "rtmp://"+bizid+".liveplay.myqcloud.com/live/"+liveId;
			String flvUrl = "http://"+bizid+".liveplay.myqcloud.com/live/"+liveId+".flv";
			String m3u8Url = "http://"+bizid+".liveplay.myqcloud.com/live/"+liveId+".m3u8";
			HashMap resultMap = new HashMap();
			resultMap.put("rtmpUrl", rtmpUrl);
			resultMap.put("flvUrl", flvUrl);
			resultMap.put("m3u8Url", m3u8Url);
			responseBodyEntity.setData(resultMap);
			responseBodyEntity.setMsg("获取播放地址成功!");
			responseBodyEntity.setState(Constants.SUCCEED);
		} catch (Exception e) {
			responseBodyEntity.setMsg("获取访问地址失败!");
			responseBodyEntity.setState(Constants.FAILURE);
			log.error("异常信息:{}",e);
		}
		return responseBodyEntity;
	}
	
	@RequestMapping("testReadFile")
	public Map testReadFile(int sdkAppId) throws Exception {
		/*File privateKeyFile = new File(keyPath+sdkAppId+"/"+privateKeyName);
	    byte[] privateKey = new byte[(int)privateKeyFile.length()];
	    FileInputStream in1 = new FileInputStream(privateKeyFile);
        in1.read(privateKey);
        in1.close();*/
		String privateKeyStr = readFile(keyPath+sdkAppId+"/"+privateKeyName);
		Map resultMap = new HashMap();
		resultMap.put("privateKeyStr",privateKeyStr);
        return resultMap;
	}
	
	
	
	public String readFile(String privateKeyPath) {
		File privateKeyFile = new File(privateKeyPath);
        byte[] privateKey = new byte[(int)privateKeyFile.length()];
        try {
            //读取私钥的内容
            //PS:不要把私钥文件暴露到外网直接下载了哦
            FileInputStream in1 = new FileInputStream(privateKeyFile);
            in1.read(privateKey);
            in1.close();
        } catch (Exception e ) {
            e.printStackTrace();
        }
        return new String(privateKey);
	}
	
	
}
